package cn.it.shop.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.it.shop.util.MessageUtil;
import cn.it.shop.util.SHA1;
import cn.it.shop.wechat.dispatcher.EventDispatcher;
import cn.it.shop.wechat.dispatcher.MsgDispatcher;

/***
 *  微信请求入口
 *  @author fys
 *
 */
@Controller
//@RequestMapping("/")
public class WeiXinController extends BaseController{
	
	private String token = "hello";
	
	/**
	 * 校验用的,
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/WeiXinSerlvet", method = RequestMethod.GET)
	public void get(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			//接收握手时微信传过来的4个参数
			String signature = request.getParameter("signature");//微信加密签名
			String timestamp = request.getParameter("timestamp");//时间戳
			String nonce = request.getParameter("nonce");//随机数
			String echostr = request.getParameter("echostr");//随机字符串
			System.out.println("签名 "+signature);
			//要加密比较的数组
			String[] str = {token,timestamp,nonce};
			// 将token、timestamp、nonce三个参数进行字典序排序：     A:65  a:97
			Arrays.sort(str);
			// 拼接成字符串的时候顺序不能变,因为腾讯服务器传过来就是这样的
			String bigStr=str[0] + str[1] + str[2];
			//进行相同的加密
			String signature2 = new SHA1().getDigestOfString(bigStr.getBytes());
			// 一定要不区分大小写比较.因为微信服务器在传入signature参数时已经转化了小写,但是API并没有提示
			if(signature.equalsIgnoreCase(signature2)){
				// 如果比对成功,则将随机字符串原样返回
				out.write(echostr);
			}else{
				out.write("非法请求");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			out.flush();
			out.close();
		}
	}

	/***
	 * 处理微信服务器发过来的请求	 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/WeiXinSerlvet", method = RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Logger logger=Logger.getLogger(WeiXinController.class);
		// 消息的接收、处理、响应
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		
		System.out.println("这是 post 方法！");
		try{
			// 响应消息(回复消息给客户)
			PrintWriter out = response.getWriter();
			out.print(" ");//默认先回复空
			Map<String, String> map=MessageUtil.parseXml(request);//处理用户发送的消息
			String msgtype=map.get("MsgType");//获取消息的类型
			String respXml = "";//接受要返回的xml格式字符串
			
			System.out.println("消息体"+map);
			//判断是消息还是事件
			if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)){
				// 调用核心业务类接收消息、处理消息
				respXml =  eventDispatcher.processEvent(map); //进入事件处理

			}else{
				// 调用核心业务类接收消息、处理消息
				respXml = msgDispatcher.processMessage(map);//进入消息处理
			}
			//System.out.println("开发者微信号: "+map.get("ToUserName"));//取出开发者微信号
			//out.print(respXml);//将xml返回给用户,这样被动回复消息就不能用了,只能用客服消息
			out.close();
			
		}catch(Exception e){
			logger.error(e,e);
		}
	}
	
	
	
	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}
	
	
	
}
